<?php
/**
 * Controller for Netflix Access
 *
 * @author brian
 */
class NetflixController extends Zend_Controller_Action {
	
	/**
	 * @var Zend_Session_Namespace 
	 */
	private $session;
	/**
	 * @var Zend_Config_Ini
	 */
	private $config;
	/**
	 * Initialization 
	 */
	public function init()
	{
		$this->session = new Zend_Session_Namespace('netflix');
		$this->config = Zend_Registry::get('api_keys')->netflix;
	}
	
	/**
	 * Start Netflix authentication 
	 */
	public function startauthAction()
	{
		// Build the callback url
		$callbackUrl = empty( $_SERVER['https'] ) ? "http://" : "https://";
		$callbackUrl .= $_SERVER['HTTP_HOST'] . "/netflix/finishauth";
		
		$config = array(
			'callbackUrl'	=> $callbackUrl,
			'siteUrl'		=> $this->config->oauth->base_url,
			'consumerKey'	=> $this->config->api->api_key,
			'consumerSecret'=> $this->config->api->shared_secret
		);
		$consumer = new Zend_Oauth_Consumer($config);

		// fetch a request token
		$token = $consumer->getRequestToken();

		// persist the token to storage
		$this->session->request_token = serialize($token);

		// redirect the user
		$consumer->redirect();
	}
	
	/**
	 * Complete Netflix authentication
	 */
	public function finishauthAction()
	{
		// Build the callback url
		$callbackUrl = empty( $_SERVER['https'] ) ? "http://" : "https://";
		$callbackUrl .= $_SERVER['HTTP_HOST'] . "/netflix/finishauth";
		
		$config = array(
			'callbackUrl'	=> $callbackUrl,
			'siteUrl'		=> $this->config->oauth->base_url,
			'consumerKey'	=> $this->config->api->api_key,
			'consumerSecret'=> $this->config->api->shared_secret
		);
		$consumer = new Zend_Oauth_Consumer($config);

		if (!empty($_GET) && isset($this->session->request_token))
		{
			$token = $consumer->getAccessToken( $_GET, unserialize($this->session->request_token));
			$this->session->token = serialize($token);

			// Now that we have an Access Token, we can discard the Request Token
			$this->session->request_token = null;
			
			var_dump($token);
			die();
		}
		else
		{
			// Mistaken request? Some malfeasant trying something?
			exit('Invalid callback request. Oops. Sorry.');
		}
	}
}